package com.crawler.waf.security.authentication.mac;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.crawler.waf.security.authens.WafUserAuthentication;
import com.crawler.waf.security.authens.UserToken;
import com.crawler.waf.security.authens.UserCenterUserDetails;
import com.crawler.waf.security.authentication.WafAuthenticationException;
import com.crawler.waf.security.services.UserDetailsService;
import com.crawler.waf.security.services.TokenService;

@Component
@Order(20)
public class MacTokenAuthenticationProvider implements AuthenticationProvider {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 负责获得用户信息，WafAuthenticationProvider注入的是UserCenterUserDetailsService
	 */
	private UserDetailsService ucUserDetailsService;

	/**
	 * tokenService负责在Uc验证用户传递token的有效性
	 */
	private TokenService ucMactokenService;


	@Autowired
	public void setUcUserDetailsService(UserDetailsService ucUserDetailsService) {
		this.ucUserDetailsService = ucUserDetailsService;
	}

	@Autowired
	public void setTokenService(@Qualifier("mac_token_service") TokenService ucMactokenService) {
		this.ucMactokenService = ucMactokenService;
	}

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	Assert.notNull(authentication, "authentication");
    	PreAuthenticatedMacTokenAuthentication tokenAuthertication = (PreAuthenticatedMacTokenAuthentication) authentication;
		//验证tokenAuthertication
		UserToken token = ucMactokenService.verifyToken(tokenAuthertication);
		UserCenterUserDetails userDetials = null;
		WafUserAuthentication authertication = null;
		if (token!=null) {
			try {
				userDetials = (UserCenterUserDetails) ucUserDetailsService.loadUserDetailsByUserId(token.getUserId());
			} catch (RuntimeException ex) {
				logger.error(ex.getMessage(), ex);
				throw new WafAuthenticationException("授权过程发生异常 " + ex.getMessage(), ex);
			}
			userDetials.getUserInfo().setUserType("Mac");
			authertication = new WafUserAuthentication(userDetials.getAuthorities());
			authertication.setAuthenticated(true);
			authertication.setDetails(userDetials);
			authertication.setToken(token);
		}
		return authertication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication == PreAuthenticatedMacTokenAuthentication.class;
    }
}
